import { useEffect, useRef } from "react"
import { Outlet } from "react-router"
import './App.css'
import { useDispatch } from "react-redux"
import { setDict } from "./store/DictSlice"

function App() {
    const divRef = useRef(null)
    const token = localStorage.getItem('token')
    const dispatch = useDispatch()

    useEffect(() => {
        if (token) return
        const location = window.location.href
        console.log(location)

        if (window.location.search.indexOf('code') > -1) {
            const usp = new URLSearchParams(window.location.search)
            const code = usp.get('code')
            fetch('http://180.76.236.114:3006/api/sso/token', {
                method: "POST",
                headers: {
                    "content-type": "application/json"
                },
                body: JSON.stringify({
                    code
                })
            }).then(res => res.json())
                .then(res => {
                    console.log(res);
                    if (res.error) {
                        console.log(res.error);
                        return
                    } else {
                        localStorage.setItem('token', res.token);
                        window.location.replace(window.location.pathname)
                    }
                }).catch((err: any) => {
                    console.log(err)
                }).finally(() => { })
            return
        }
        window.location.href = `
            ${import.meta.env.VITE_SSO_LOGIN_URL}?${import.meta.env.VITE_REDIRECT_PROP}=
            ${encodeURIComponent(location)}
        `
    }, [])

    useEffect(() => {
        fetch('http://180.76.236.114:3006/me-api/dict', {
            method: "GET",
            headers: {
                'Authorization': `Bearer ${token}`
            }
        }).then(res => res.json())
            .then(res => {
                dispatch(setDict(res.data))
            })
    }, [])

    return (
        <>
            <div
                className="h-[100%] overflow-y-auto"
                ref={divRef}
            >
                <Outlet />
            </div>
        </>
    )
}
export default App